package com.whoyx.jiebing.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.crypto.digest.MD5;

import java.util.Map;
import java.util.TreeSet;

/**
 * @author Stone
 * @date 2022/9/26
 */
public class SignUtils {

    private static final String SIGN_PARAM = "sign";

    public static String generateSign(Object o, String key) {
        Map<String, Object> params = BeanUtil.beanToMap(o);
        StringBuilder sb = new StringBuilder();
        TreeSet<String> treeSet = new TreeSet<>(params.keySet());
        for (String paramKey : treeSet) {
            Object value = params.get(paramKey);
            if (null != value && !paramKey.equals(SIGN_PARAM)) {
                sb.append(paramKey).append("=").append(value).append("&");
            }
        }
        sb.append("key=").append(key);
        return new Digester(DigestAlgorithm.SHA256).digestHex(sb.toString()).toUpperCase();
    }

    public static void validatedSign(Object o, String key) {
        Map<String, Object> params = BeanUtil.beanToMap(o);
        StringBuilder sb = new StringBuilder();
        Object signValue = null;
        for (String paramKey : new TreeSet<>(params.keySet())) {
            Object value = params.get(paramKey);
            if (paramKey.equals(SIGN_PARAM)) {
                signValue = value;
                continue;
            }
            if (null != value) {
                sb.append(paramKey).append("=").append(value).append("&");
            }
        }
        sb.append("key=").append(key);
        if (null == signValue) {
            throw new BaseException(403, "缺少签名参数");
        }
        String sign = MD5.create().digestHex(sb.toString()).toUpperCase();
        boolean r = sign.equals(signValue);
        if (!r) {
            throw new BaseException(403, "签名校验失败");
        }
    }

    public static void main(String[] args) {
        String sign = MD5.create().digestHex("appId=whgqck843vbbl1zf2h&openId=wh_76767676&key=f90f27c4a6843d0f81f91237558e1222eab06752").toUpperCase();
        System.out.println("sign: " + sign);
    }

}
